<template>
  <div>
    <!--        模拟考试{{subject_id}}{{subject_name}}{{currentItem}}-->
    <el-tabs v-model="tabsActiveName" class="demo-tabs">
      <el-tab-pane
        v-for="item in subjectTabs"
        :label="item.name"
        :name="String(item.id)"
      >
        <div v-if="mockExamList && mockExamList.rows && mockExamList.rows.length">
          <div v-for="item in mockExamList.rows">
            <el-row style="margin-bottom: 20px;padding:10px" justify="space-between">
              <el-col :span="6">
                <img style="width: 100%" :src="item.bannerPic" alt="" />
              </el-col>
              <el-col :span="17">
                <div
                        style="
                  display: flex;
                  justify-content: space-between;
                  height: 100%;
                "
                >
                  <div
                          style="
                    display: flex;
                    flex-direction: column;
                    justify-content: space-around;
                    height: 100%;
                  "
                  >
                    <p style="font-size: 16px;font-weight: bold">{{ item.type }}</p>
                    <p style="font-size: 14px">{{ item.name }}</p>
                    <div style="font-size: 14px" v-html="item.describe"></div>
                  </div>
                  <div style="display: flex; align-items: center">
                    <el-button
                            size="large"
                            type="primary"
                            @click="toMockExam(item)"
                    >开始做题</el-button
                    >
                  </div>
                </div>
              </el-col>
            </el-row>
          </div>
        </div>
        <el-empty v-else description="暂无考试" />
        <el-row>
          <div class="ExerciseTab">
            <el-tabs v-model="activeName" class="demo-tabs">
              <el-tab-pane label="模考记录" name="default">
                <div
                  v-if="
                    MockPaperLogList &&
                    MockPaperLogList.rows &&
                    MockPaperLogList.rows.length
                  "
                >
                  <div v-for="item in MockPaperLogList.rows.sort((a,b) => a.updatedAt - b.updatedAt)">
                    <div @click="lookMockPaper(item)" class="ExerciseItem">
                      <div>
                        <span class="name">{{ item.name }}</span>
                      </div>
                      <div class="exam_history">
                        <span>{{
                          proxy.$filters.dateTimeFormat(item.updatedAt)
                        }}</span>
                        <span
                          >正确率:{{ item.correctS ? item.correctS : 0 }}%</span
                        >
                        <span>客观题得分:{{ item.objectiveScore }}</span>
                        <span>总分:{{ item.totalScore }}</span>
                        <span style="color: rgba(11, 67, 128, 1);">{{
                          item.fraction == null ? "未完成" : "已完成"
                        }}</span>
                      </div>
                    </div>
                  </div>
                </div>
                <el-empty v-else description="暂无数据" />
              </el-tab-pane>
            </el-tabs>
          </div>
        </el-row>
        <el-row>
          <div v-if="MockPaperLogList.pagination">
            <el-pagination
              background
              v-model:currentPage="currentPage"
              :page-size="pageSize"
              layout="total, prev, pager, next"
              :total="MockPaperLogList.pagination.count"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </div>
        </el-row>
      </el-tab-pane>
    </el-tabs>
    <el-dialog
      v-model="dialogFormVisible"
      custom-class="dialogFormVisible"
      width="20%"
      :center="true"
      :show-close="false"
    >
      <template #title>
        <span style="font-size: 24px;color: rgba(3, 144, 252, 1)">座位号：021</span>
      </template>
      <el-form
        :label-position="'top'"
        ref="mockFormRef"
        :model="mockForm"
        status-icon
        :rules="mockRules"
        label-width="120px"
        class="demo-ruleForm"
      >
        <el-form-item label="准考证号" prop="exam_code">
          <el-input v-model="mockForm.exam_code" autocomplete="off" />
        </el-form-item>
        <el-form-item label="证件号" prop="card_id">
          <el-input v-model="mockForm.card_id" autocomplete="off" />
        </el-form-item>
        <el-form-item>
          <el-button style="width: 45%" @click="resetForm(mockFormRef)"
            >重置</el-button
          >
          <el-button
            style="width: 45%"
            type="primary"
            @click="submitForm(mockFormRef)"
            >进入考试</el-button
          >
        </el-form-item>
        <el-form-item>
          <div style="color: rgba(148, 148, 148, 1)">
            <p>说明：此准考证号、报名序号仅供考生模拟使用，</p>
            <p>非真实准考证号，报名序号。</p>
          </div>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import goBackHistory from "../../../utils/hook/goBackHistory";
import {
  createdTestPaper,
  testPaperLogList,
  subjectList,
  createdTestPaperMockTest,
} from "@/api/api";
import {
  reactive,
  toRefs,
  getCurrentInstance,
  watch,
  onMounted,
  ref,
} from "vue";
import { useRouter } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";

export default {
  name: "index",
  props: {
    subject_id: {
      type: Number,
    },
    subject_name: {
      type: String,
    },
    currentItem: {
      type: String,
    },
    activeCourse: {
      type: String,
    },
  },
  setup(props, { emit }) {
    let router = useRouter();
    const { proxy } = getCurrentInstance();
    let data = reactive({
      subjectName: "",
      subjectTabs: [],
      tabsActiveName: null,
      pageSize: 10,
      currentPage: 1,
      mockExamList: [], //模拟试卷列表
      MockPaperLogList: [], //模拟考试记录列表
      activeName: "default",
      dialogFormVisible: false,
      currentMockId: null,
      scopeTime:null,
      exam_name:'',//试卷名称
      mockForm: {
        exam_code: "*********",
        card_id: "*********",
      },
    });
    const mockFormRef = ref(null);

    //科目列表
    let getAllSubjectList = () => {
      let course_id = localStorage.getItem("activeCourse");
      subjectList({ courseID: course_id }).then((res) => {
        console.log("科目列表", res);
        data.subjectTabs = res.data;
        data.tabsActiveName = String(res.data[0].id);
      });
    };
    getAllSubjectList();

    const validateExamCode = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("准考证号不能为空"));
      } else {
        callback();
      }
    };
    const validateCardId = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("证件号码不能为空"));
      } else {
        callback();
      }
    };

    const mockRules = reactive({
      exam_code: [{ validator: validateExamCode, trigger: "blur" }],
      card_id: [{ validator: validateCardId, trigger: "blur" }],
    });

    //模拟考试
    let MockExamList = () => {
      createdTestPaper({
        subjectID: data.tabsActiveName,
        type: "模拟试卷",
      }).then((res) => {
        console.log("模拟考试", res);
        data.mockExamList = res.data;
      });
    };

    //模拟考试历史记录
    let getMockPaperLogList = () => {
      let params = {
        subjectID: Number(data.tabsActiveName),
        type: "模拟试卷",
        pageSize: data.pageSize,
        page: data.currentPage,
      };
      testPaperLogList(params).then((res) => {
        console.log("模拟考试记录列表", res);
        data.MockPaperLogList = res.data;
      });
    };
    onMounted(() => {
      // MockExamList();
      // getMockPaperLogList();
    });

    let toMockExam = (item) => {
      ElMessageBox.confirm(
              `本场练习共${item.maxTopicNum}题，总时长${Number.parseInt(item.scopeTime / 60)}分钟`,
              '温馨提示',
              {
                confirmButtonText: '确认',
                cancelButtonText: '取消',
                type: 'warning',
              }
      )
              .then(() => {
                data.dialogFormVisible = true;
                data.currentMockId = item.id;
                data.scopeTime = item.scopeTime;
                data.exam_name = item.name
              })
              .catch(() => {
                ElMessage({
                  type: 'info',
                  message: '已取消',
                })
              })
    };

    const submitForm = (formEl) => {
      if (!formEl) return;
      formEl.validate((valid) => {
        if (valid) {
          let params = router.currentRoute.value;
          let currentItem = props.currentItem;
          goBackHistory.addCurrentPageParams(params, currentItem);
          console.log("模拟考试id", data.currentMockId);
          router.push({
            name: "MockExam",
            params: {
              subject_name: props.subject_name,
              id: data.currentMockId,
              exam_code: data.mockForm.exam_code,
              card_id: data.mockForm.card_id,
              method: "createdTestPaperMockTest",
              fraction: "null",
              scopeTime:data.scopeTime,
              exam_name:data.exam_name
            },
          });
        } else {
          console.log("error submit!");
          return false;
        }
      });
    };

    const resetForm = (formEl) => {
      if (!formEl) return;
      formEl.resetFields();
    };

    const handleSizeChange = (val) => {
      console.log(`${val} items per page`);
      data.pageSize = val;
      getMockPaperLogList();
    };
    const handleCurrentChange = (val) => {
      console.log(`current page: ${val}`);
      data.currentPage = val;
      getMockPaperLogList();
    };

    let lookMockPaper = (item) => {
      if (item.fraction == null) {
        ElMessageBox.confirm("是否继续上次未完成的试卷？", "温馨提示", {
          confirmButtonText: "继续作答",
          cancelButtonText: "退出",
          type: "warning",
        }).then(() => {
          let params = router.currentRoute.value;
          let currentItem = props.currentItem;
          goBackHistory.addCurrentPageParams(params, currentItem);
          router.push({
            name: "MockExam",
            params: {
              subject_name: props.subject_name,
              id: item.id,
              exam_code: data.mockForm.exam_code,
              card_id: data.mockForm.card_id,
              method: "testPaperDetailLog",
              fraction: item.fraction == null ? "null" : item.fraction,
              scopeTime:item.scopeTime,
              exam_name:data.subjectName
            },
          });
        });
      } else {
        router.push({
          name: "MockExam",
          params: {
            subject_name: props.subject_name,
            id: item.id,
            exam_code: data.mockForm.exam_code,
            card_id: data.mockForm.card_id,
            method: "testPaperDetailLog",
            fraction: item.fraction == null ? "null" : item.fraction,
            scopeTime:item.scopeTime,
            exam_name:data.subjectName
          },
        });
      }
    };

    watch(
      () => data.tabsActiveName,
      () => {
        if (data.tabsActiveName) {
          data.subjectName = data.subjectTabs.filter(
            (item) => item.id == Number(data.tabsActiveName)
          )[0].name;
          emit("changeSubjectName", data.subjectName);
          MockExamList();
          getMockPaperLogList();
        }
      }
    );

    watch(
      () => props.activeCourse,
      () => {
        getAllSubjectList();
        getMockPaperLogList();
      }
    );

    return {
      mockFormRef,
      proxy,
      lookMockPaper,
      handleSizeChange,
      handleCurrentChange,
      submitForm,
      resetForm,
      mockRules,
      toMockExam,
      ...toRefs(data),
      MockExamList,
    };
  },
};
</script>

<style scoped>
.exam_history :not(:last-child) {
  margin-right: 20px;
}
.exam_history :not(:first-child) {
  font-weight: 400;
  font-size: 12px;
  color: rgba(153, 153, 153, 1);
  /* color: rgba(42, 130, 228, 1); */
}
.exam_history :first-child {
  font-size: 12px;
  color: rgba(153, 153, 153, 1);
}
.ExerciseItem .name {
  color: rgba(11, 67, 128, 1);
  font-size: 14px;
  font-weight: 400;
}
.ExerciseTab {
  width: 100%;
  margin-bottom: 20px;
}
.dialogFormVisible {
  border-radius: 20px;
}

.ExerciseItem {
  display: flex;
  justify-content: space-between;
  padding: 5px 20px;
  background-color: rgba(248, 248, 248, 1);
  margin-bottom: 10px;
  border-radius: 10px;
  cursor: pointer;
}
</style>
